package com.hello.common.security.service;

import com.hello.common.core.constant.CacheConstants;
import com.hello.common.core.constant.SecurityConstants;
import com.hello.common.core.utils.JwtUtils;
import com.hello.common.core.utils.ServletUtils;
import com.hello.common.core.utils.StringUtils;
import com.hello.common.core.utils.ip.IpUtils;
import com.hello.common.core.utils.uuid.IdUtils;
import com.hello.common.redis.service.RedisService;
import com.hello.common.security.utils.SecurityUtils;
import com.hello.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 * 
 * @author hello
 */
@Component
public class TokenService
{
    @Autowired
    private RedisService redisService;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private final static long expireTime = CacheConstants.EXPIRATION;
    
    private final static long refreshTokenExpireTime = CacheConstants.REFRESH_TOKEN_EXPIRATION;

    private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;
    
    private final static String REFRESH_TOKEN = CacheConstants.REFRESH_TOKEN_KEY;

    private final static Long MILLIS_MINUTE_TEN = CacheConstants.REFRESH_TIME * MILLIS_MINUTE;

    /**
     * 创建令牌
     */
    public Map<String, Object> createToken(LoginUser loginUser)
    {
        // 生成访问令牌和刷新令牌
        String token = IdUtils.fastUUID();
        String refreshToken = IdUtils.fastUUID();
        
        Long userId = loginUser.getSysUser().getUserId();
        String userName = loginUser.getSysUser().getUserName();
        loginUser.setToken(token);
        loginUser.setRefreshToken(refreshToken); // 添加刷新令牌
        loginUser.setUserid(userId);
        loginUser.setUsername(userName);
        loginUser.setIpaddr(IpUtils.getIpAddr());
        
        // 缓存用户信息
        refreshToken(loginUser);
        // 缓存刷新令牌关联的用户ID
        cacheRefreshToken(refreshToken, userId, userName);

        // Jwt存储信息
        Map<String, Object> claimsMap = new HashMap<String, Object>();
        claimsMap.put(SecurityConstants.USER_KEY, token);
        claimsMap.put(SecurityConstants.DETAILS_USER_ID, userId);
        claimsMap.put(SecurityConstants.DETAILS_USERNAME, userName);

        // 接口返回信息
        Map<String, Object> rspMap = new HashMap<String, Object>();
        rspMap.put("access_token", JwtUtils.createToken(claimsMap));
        rspMap.put("expires_in", expireTime);
        
        // 添加刷新令牌信息
        Map<String, Object> refreshClaimsMap = new HashMap<String, Object>();
        refreshClaimsMap.put(SecurityConstants.USER_KEY, refreshToken);
        refreshClaimsMap.put(SecurityConstants.DETAILS_USER_ID, userId);
        refreshClaimsMap.put(SecurityConstants.DETAILS_USERNAME, userName);
        rspMap.put("refresh_token", JwtUtils.createToken(refreshClaimsMap));
        rspMap.put("refresh_expires_in", refreshTokenExpireTime);
        
        return rspMap;
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser()
    {
        return getLoginUser(ServletUtils.getRequest());
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request)
    {
        // 获取请求携带的令牌
        String token = SecurityUtils.getToken(request);
        return getLoginUser(token);
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(String token)
    {
        LoginUser user = null;
        try
        {
            if (StringUtils.isNotEmpty(token))
            {
                String userkey = JwtUtils.getUserKey(token);
                user = redisService.getCacheObject(getTokenKey(userkey));
                return user;
            }
        }
        catch (Exception e)
        {
        }
        return user;
    }
    
    /**
     * 通过刷新令牌获取登录用户信息
     *
     * @param refreshToken 刷新令牌
     * @return 登录用户信息
     */
    public Map<String, Object> getUserInfoByRefreshToken(String refreshToken)
    {
        if (StringUtils.isEmpty(refreshToken))
        {
            return null;
        }
        try
        {
            String userKey = JwtUtils.getUserKey(refreshToken);
            String userInfoKey = getRefreshTokenKey(userKey);
            Map<String, Object> userInfo = redisService.getCacheObject(userInfoKey);
            return userInfo;
        }
        catch (Exception e)
        {
            return null;
        }
    }
    
    /**
     * 使用刷新令牌创建新的访问令牌
     *
     * @param refreshToken 刷新令牌
     * @return 新的令牌信息
     */
    public Map<String, Object> refreshTokenAndCreateNew(String refreshToken)
    {
        Map<String, Object> userInfo = getUserInfoByRefreshToken(refreshToken);
        if (userInfo == null)
        {
            return null;
        }
        
        // 安全地将Integer或Long转换为Long类型
        Long userId;
        Object userIdObj = userInfo.get("userId");
        if (userIdObj instanceof Integer) {
            userId = ((Integer) userIdObj).longValue();
        } else {
            userId = (Long) userIdObj;
        }
        
        String userName = (String) userInfo.get("userName");
        
        // 创建登录用户对象
        LoginUser loginUser = new LoginUser();
        com.hello.system.api.dto.SysUserDTO sysUser = new com.hello.system.api.dto.SysUserDTO();
        sysUser.setUserId(userId);
        sysUser.setUserName(userName);
        loginUser.setSysUser(sysUser);
        
        // 创建新的访问令牌和刷新令牌
        return createToken(loginUser);
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUser loginUser)
    {
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken()))
        {
            refreshToken(loginUser);
        }
    }

    /**
     * 删除用户缓存信息
     */
    public void delLoginUser(String token)
    {
        if (StringUtils.isNotEmpty(token))
        {
            try {
                String userkey = JwtUtils.getUserKey(token);
                redisService.deleteObject(getTokenKey(userkey));
            } catch (Exception e) {
                // 如果解析令牌失败，尝试直接删除以token为key的缓存
                redisService.deleteObject(getTokenKey(token));
            }
        }
    }
    
    /**
     * 删除刷新令牌
     */
    public void delRefreshToken(String refreshToken)
    {
        if (StringUtils.isNotEmpty(refreshToken))
        {
            try {
                String userkey = JwtUtils.getUserKey(refreshToken);
                redisService.deleteObject(getRefreshTokenKey(userkey));
            } catch (Exception e) {
                // 如果解析令牌失败，尝试直接删除以refreshToken为key的缓存
                redisService.deleteObject(getRefreshTokenKey(refreshToken));
            }
        }
    }

    /**
     * 验证令牌有效期，相差不足120分钟，自动刷新缓存
     *
     * @param loginUser
     */
    public void verifyToken(LoginUser loginUser)
    {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
        {
            refreshToken(loginUser);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser)
    {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisService.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
    }
    
    /**
     * 缓存刷新令牌关联的用户信息
     *
     * @param refreshToken 刷新令牌
     * @param userId 用户ID
     * @param userName 用户名
     */
    private void cacheRefreshToken(String refreshToken, Long userId, String userName)
    {
        Map<String, Object> userInfo = new HashMap<>();
        // 确保存储Long类型的userId，避免类型转换问题
        userInfo.put("userId", userId);
        userInfo.put("userName", userName);
        
        String userKey = getRefreshTokenKey(refreshToken);
        redisService.setCacheObject(userKey, userInfo, refreshTokenExpireTime, TimeUnit.MINUTES);
    }

    private String getTokenKey(String token)
    {
        return ACCESS_TOKEN + token;
    }
    
    private String getRefreshTokenKey(String token)
    {
        return REFRESH_TOKEN + token;
    }
}